package bug.dao.hibernate;

import bug.dao.api.IBaseDao;
import bug.persistent.PO;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.util.List;

public abstract class BaseDaoHibernate<T extends PO> extends HibernateDaoSupport implements IBaseDao<T> {

    protected final Log log = LogFactory.getLog(getClass());
    public abstract Class<T> domainClass();

    @SuppressWarnings("unchecked")
    public T getById(long id) {
        log.debug(String.format(">>> getById(%d) for: %s", id, domainClass().getName()));
        HibernateTemplate ht = getHibernateTemplate();
        return (T) ht.get(domainClass(), id);
    }

    public List<T> getAll() {
        log.debug(String.format(">>> getAll() for: %s", domainClass().getName()));
        return getHibernateTemplate().find("FROM " + domainClass().getName());
    }

    public void save(T e) {
        getHibernateTemplate().saveOrUpdate(e);
    }

    public T merge(T e) {
        return (T)getHibernateTemplate().merge(e);
    }
}
